<template>
	<div>
		<el-form
			:model="ruleForm"
			:rules="rules"
			ref="ruleForm"
			label-width="100px"
			class="demo-ruleForm"
		>
			<el-form-item label="用户名称" prop="username">
				<el-input v-model="ruleForm.username"></el-input>
			</el-form-item>
			<el-form-item label="用户密码" prop="password">
				<el-input v-model="ruleForm.password" type="password"></el-input>
			</el-form-item>
			<el-form-item label="电子邮箱" prop="email">
				<el-input v-model="ruleForm.email"></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="mobile">
				<el-input v-model="ruleForm.mobile"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')"
					>立即添加</el-button
				>
				<el-button @click="resetForm('ruleForm')">重置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	// import axios from "axios";
	import { addusersPost } from "@/http/request.js";
	export default {
		data() {
			var checkEmail = (rule, value, callback) => {
				if (value.indexOf("@") == -1 || value.indexOf(".") == -1) {
					callback(new Error("输入的邮箱必须含有@和."));
				} else {
					callback();
				}
			};
			var checkMobile = (rule, value, callback) => {
				let reg = /^1[3456789]\d{9}$/;
				if (!reg.test(value)) {
					callback(new Error("手机号以1开头的11位数字"));
				} else {
					callback();
				}
			};
			return {
				ruleForm: {
					username: "",
					password: "",
					email: "",
					mobile: "",
				},
				rules: {
					username: [
						{ required: true, message: "请输入用户名称", trigger: "blur" },
						{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
					],
					password: [
						{ required: true, message: "请输入密码", trigger: "blur" },
						{ min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
					],
					email: [
						{ required: true, message: "请输入邮箱", trigger: "blur" },
						// validator: checkEmail是自定义校验
						{ validator: checkEmail, trigger: "blur" },
					],
					mobile: [
						{ required: true, message: "请输入手机号", trigger: "blur" },
						{ validator: checkMobile, trigger: "blur" },
					],
				},
			};
		},
		methods: {
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						addusersPost("users", {
							username: this.ruleForm.username,
							password: this.ruleForm.password,
							email: this.ruleForm.email,
							mobile: this.ruleForm.mobile,
						})
							.then((res) => {
								let { meta } = res.data;
								if (meta.status == 201) {
									this.$message.success(meta.msg);
									this.$emit("addok");
								} else {
									this.$message.error(meta.msg);
								}
							});
					} else {
						this.$message.error(" error submit!");
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
		},
	};
</script>


<style lang="less" scoped>
</style>